<style lang="less">
</style>

<template>
    <div>
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80" >
            <Row>
                <Col span="14">
                    <FormItem label="课程视频内容" prop="media_url" :label-width="100">
                        <div>
                            <Upload 
                            ref="uploadVideo"
                            :format="['mp4']"
                            :max-size="409600"
                            :on-format-error="handleVideoFormatError"
                            :on-exceeded-size="handleVideoMaxSize"
                            :on-success="handleVideoUploadSuccess"
                            :on-remove="handleRemoveVideo" 
                            :before-upload="handleBeforeUpload"
                            :default-file-list="defaultVideoList"
                            :headers= "headers" 
                            type="drag" 
                            :action="videoAction" >
                                <div style="padding: 20px 0">
                                    <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                    <p>点击或将文件拖拽到这里上传</p>
                                </div>
                            </Upload>
                            <Input v-model="formValidate.media_url" v-show="false"></Input>
                        </div>
                    </FormItem>
                </Col>
                <Col span="10">
                    <FormItem label="课程名称" prop="name">
                        <Input v-model="formValidate.name" placeholder="请输入课程名称"></Input>
                    </FormItem>
                    <FormItem label="课程分类" prop="class_id" >
                        <Select v-model="formValidate.class_id" placeholder="请选择课程分类">
                            <Option v-for="item in classList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="可得学分" prop="points">
                        <Input v-model.number="formValidate.points" placeholder="请输入学习课程可得学分"></Input>
                    </FormItem>
                    <FormItem label="课程简介" prop="describe">
                        <Input v-model="formValidate.describe" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入课程介绍"></Input>
                    </FormItem>
                    <FormItem label="排序值" prop="listorder">
                        <Input v-model.number="formValidate.listorder" placeholder="请输入课程排序值"></Input>
                    </FormItem>
                    <FormItem label="课程首图" prop="headimg">
                        <div>
                            <Upload 
                            ref="upload"
                            :max-size="2048"
                            :format="['jpg','jpeg','png']"
                            :on-format-error="handleFormatError"
                            :on-exceeded-size="handleMaxSize"
                            :on-success="handleUploadSuccess"
                            :on-remove="handleRemoveFile"
                            :default-file-list="defaultList"
                            :on-preview="handlePreview"  
                            type="drag"
                            :headers= "headers"
                            :action="headimgAction" >
                                <div style="padding: 20px 0">
                                    <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                    <p>点击或将文件拖拽到这里上传</p>
                                </div>
                            </Upload>
                            <Input v-model="formValidate.headimg" v-show="false"</Input>
                        </div>
                    </FormItem>
                    <FormItem>
                        <Button type="primary" @click="handleSubmit('formValidate')" :disabled="isDisabled">提交</Button>
                        <Button type="ghost" @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
                    </FormItem>
                </Col>
            </Row>
            <Modal title="预览图片" v-model="visible" class="preview">
                <img :src="pre_img_url" style="width: 100%">
                <div slot="footer"></div>
            </Modal>
        </Form>
    </div>
</template>

<script>
import http from '../../../libs/http';
import Cookies from 'js-cookie';
export default {
        data () {
            return {
                headimgAction: this.host + 'admin/course/uploadHeadImg',
                videoAction: this.host + 'admin/course/uploadVideo',
                isDisabled: false,
                classList: [],  //课程分类列表
                uploadList: [], //上传首图列表
                uploadVideoList: [],  //上传视频列表
                defaultVideoList: [{name:'',url:''}], //已上传视频列表
                defaultList: [{name:'',url:''}],   //已上传首图列表
                visible: false, //预览窗口
                pre_img_url: '', //预览图片路径
                formValidate: {
                    id: '',
                    name: '',
                    describe: '',
                    class_id: '',
                    points:'',
                    listorder: '',
                    headimg:'',
                    media_url: ''
                },
                ruleValidate: {
                    name: [
                        { required: true, message: '课程名不能为空', trigger: 'blur' }
                    ],
                    class_id: [
                        { type: 'number', required: true, message: '请选择课程分类', trigger: 'change' }
                    ],
                    describe: [
                        { required: true, message: '请输入课程简介', trigger: 'blur' },
                        { type: 'string', min: 1, message: '课程简介不能为空', trigger: 'blur' }
                    ],
                    points: [
                        { type:'number', required: true, message: '学习课程可得学分为空或格式错误', trigger: 'blur'},
                    ],
                    listorder: [
                        {type: 'number', message: '请输入数字', trigger: 'blur'}
                    ],
                    headimg: [
                        { required: true, message: '课程首图不能为空', trigger: 'blur'}
                    ],
                    media_url: [
                        { required: true, message: '课程视频不能为空', trigger: 'blur'}
                    ]
                }
            }
        },
        methods: {
            handleSubmit (name) {   //提交按钮点击事件
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        //提交后台
                        var data = {
                            id: this.formValidate.id,
                            name: this.formValidate.name,
                            describe: this.formValidate.describe,
                            class_id: this.formValidate.class_id,
                            class_type: 1, //课程类型为视频
                            points: this.formValidate.points,
                            listorder: this.formValidate.listorder,
                            headimg: this.formValidate.headimg,
                            media_url: this.formValidate.media_url
                        }
                        this.apiPost('admin/course/update', data).then((res) => {
                            if (res.code != 200) {
                                this.handleError(res);
                            } else {
                                this.$Message.success('编辑课程成功');
                                this.handleReset(name);
                                this.$refs.upload.clearFiles();
                                this.$refs.uploadVideo.clearFiles();
                                this.uploadVideoList = [];  //清空上传视频列表
                                this.uploadList = []; //清空上传首图列表
                                this.$emit('editVideoCancel');
                            }
                        })
                    } else {
                        this.$Message.error('表单验证失败!');
                    }
                })
            },
            handleReset (name) {   //重置表单
                this.$refs[name].resetFields();
            },
            getClassCate() {   //获取课程分类
                var that = this
                var url = 'admin/classCate/index/type/1';
                this.apiGet(url).then((res) => {
                    if (res.code != 200) {
                        this.handleError(res);
                    } else {
                        that.classList = res.data.list;
                    }
                })
            },
            getCourseInfo(id) {  //获取课程信息
                var that = this;
                var url = 'admin/course/read/' + id;
                this.apiGet(url).then((res) => {
                    if (res.code != 200) {
                        this.handleError(res);
                    } else {
                        that.formValidate = {
                            id: res.data.id,
                            name: res.data.name,
                            describe: res.data.describe,
                            class_id: res.data.class_id,
                            points: res.data.points,
                            listorder: res.data.listorder,
                            headimg: res.data.headimg,
                            media_url: res.data.media_url
                        }
                        //获取已上传的图片及文件名
                        var str = res.data.headimg;
                        that.defaultList[0].url = str;
                        that.defaultList[0].name = str.substring(str.length-32, str.length);
                        var str2 = res.data.media_url;
                        that.defaultVideoList[0].name = str2.substring(str2.length-32, str2.length);
                        that.defaultVideoList[0].url = str2;
                        this.getClassCate();
                    }
                })
            },
            handleBeforeUpload () {   //上传前处理
                const check = this.uploadList.length < 1;
                const checkVideo = this.uploadVideoList.length < 1;
                if (!check) {
                    this.$Notice.warning({
                        title: '每次仅能上传一张图片'
                    });
                } else if (!checkVideo) {
                    this.$Notice.warning({
                        title: '每次仅能上传一部视频'
                    })
                } else {
                    this.isDisabled = true;
                }
                return check;
            },
            handleFormatError (file) { //图片上传格式错误
                this.isDisabled = false;
                this.$Notice.warning({
                    title: '文件格式不正确',
                    desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
                });
            },
            handleMaxSize (file) {  //图片过大
                this.isDisabled = false;
                this.$Notice.warning({
                    title: '超出文件大小限制',
                    desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
                });
            },
            handleVideoFormatError (file) { //视频上传格式错误
                this.isDisabled = false;
                this.$Notice.warning({
                    title: '文件格式不正确',
                    desc: '文件 ' + file.name + ' 格式不正确，请上传MP4格式的视频。'
                });
            },
            handleVideoMaxSize(file) {  //视频过大
                this.isDisabled = false;
                this.$Notice.warning({
                    title: '超出视频文件大小限制',
                    desc: '文件 ' + file.name + ' 太大，不能超过 400M。'
                });
            },
            handleUploadSuccess (res, file) { //图片上传成功处理方法
                if (res.code != 200) {
                    this.handleError(res);
                } else {
                    this.isDisabled = false;
                    this.formValidate.headimg = res.data;
                    file.url = res.data;
                }
            },
            handleVideoUploadSuccess (res, file) {  //视频上传成功处理方法
                this.isDisabled = false;
                this.formValidate.media_url = res.data;
                file.url = res.data;
            },
            handleRemoveFile (file) {  //删除已上传文件
                this.$Modal.confirm({
                    width: "200",
                    content: '确认是否删除,删除后无法恢复',
                    onOk: () => {
                        var data = { url: file.url }
                        this.apiPost('admin/course/deleteFile', data).then((res) => {
                            if (res.code != 200) {
                                this.handleError(res);
                            } else {
                                this.formValidate.headimg = '';
                            }
                        });
                    }
                });
            },
            handleRemoveVideo (file) {  //删除已上传视频
                this.$Modal.confirm({
                    width: "200",
                    content: '确认是否删除,删除后无法恢复',
                    onOk: () => {
                        var data = { url: file.url }
                        this.apiPost('admin/course/deleteFile', data).then((res) => {
                            if (res.code != 200) {
                                this.handleError(res);
                            } else {
                                this.formValidate.media_url = '';
                            }
                        })
                    }
                });
            },
            handlePreview (file) {  //预览上传图片
                this.pre_img_url = file.url;
                this.visible = true;
            }
        },
        //计算属性,返回header头
        computed: {
            headers() {
                return {
                    'authKey': Cookies.get('authKey'),
                    'sessionId': Cookies.get('sessionId')
                }
            }
        },
        mixins: [http],
    }
</script>

